Fancy Histograms!

We’ll start by making some histograms.

#install.packages("dslabs")
library(dslabs) 
data(heights)
glimpse(heights)
## Rows: 1,050
## Columns: 2
## $ sex    <fct> Male, Male, Male, Male, Male, Female, Female, Female, Female, M…
## $ height <dbl> 75, 70, 68, 74, 61, 65, 66, 62, 66, 67, 72, 72, 69, 68, 69, 66,…

This data is the heights of humans, divided by their biological sex.

Use ggplot to make a histogram of all of the heights:

ggplot(heights, aes(x = height)) + geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Change up the binwidth and see how the plots change. Try 1, 5, 10, and 20

ggplot(heights, aes(x = height)) + geom_histogram(binwidth = 1)

ggplot(heights, aes(x = height)) + geom_histogram(binwidth = 5)

ggplot(heights, aes(x = height)) + geom_histogram(binwidth = 10)

ggplot(heights, aes(x = height)) + geom_histogram(binwidth = 20)

Smooth this out to an emperical density with geom_density()

ggplot(heights, aes(x = height)) + geom_density()

Use a new argument in the aes(), group = to split this density by sex

ggplot(heights, aes(x = height, group = sex)) + geom_density()

OR we can do it with color or fill. If you say you want to color by sex, R knows that you want a different curve for each of them.

ggplot(heights, aes(x = height, fill = sex)) + geom_density()

If you’ve used fill, then there is now a slight issue that they are overlapped. We can fix this with alpha transparency!

ggplot(heights, aes(x = height, fill = sex)) + geom_density(alpha = 0.5)

Let’s make some boxplots of the same information.

ggplot(heights) + geom_boxplot(aes(x = height, y = sex))

Quantatitive summaries:

Find the mean and median overall.

heights %>% summarise(mean_height = mean(height), median_height = median(height))
##   mean_height median_height
## 1    68.32301          68.5

Find the mean and median for both groups.

heights %>% group_by(sex) %>%  summarise(mean_height = mean(height), median_height = median(height))
## # A tibble: 2 × 3
##   sex    mean_height median_height
##   <fct>        <dbl>         <dbl>
## 1 Female        64.9          65.0
## 2 Male          69.3          69

How tall is the tallest woman? How short is the shortest man?

heights %>% group_by(sex) %>% summarise(max(height), min(height))
## # A tibble: 2 × 3
##   sex    `max(height)` `min(height)`
##   <fct>          <dbl>         <dbl>
## 1 Female          79              51
## 2 Male            82.7            50

Presidental Elections Data

# install.packages("pscl")
library(pscl) # loads in the package that has this data. 
## Classes and Methods for R originally developed in the
## Political Science Computational Laboratory
## Department of Political Science
## Stanford University (2002-2015),
## by and under the direction of Simon Jackman.
## hurdle and zeroinfl functions by Achim Zeileis.
## You might need to install this...

# data for presidental elections
votedata <-  presidentialElections
glimpse(votedata)
## Rows: 1,097
## Columns: 4
## $ state   <chr> "Alabama", "Arizona", "Arkansas", "California", "Colorado", "C…
## $ demVote <dbl> 84.76, 67.03, 86.27, 58.41, 54.81, 47.40, 48.11, 74.49, 91.60,…
## $ year    <int> 1932, 1932, 1932, 1932, 1932, 1932, 1932, 1932, 1932, 1932, 19…
## $ south   <lgl> TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FAL…

Let’s look at the democratic vote by state for 2000. We can’t use geom_bar for a bar chart, since we have the category in one variable and the “height” of the bar in another. We need geom_col()

Make a bar graph of the democratic vote by state in 2000.

ggplot(votedata %>% filter(year == 2000)) + geom_col(aes(x = state, y = demVote))

Well this looks awful. We have two options: swap the x and y or the more fun sounding… Coordinate flip!

Use coord_flip() on the previous graph to make it better.

ggplot(votedata %>% filter(year == 2000)) + geom_col(aes(x = state, y = demVote)) + coord_flip()

I don’t love the squashed together coordinates, but it’s a display window issue.

So. This is a helpful graph, but it would be more helpful if it was ordered. Use x = reorder(x_variable, y_variable) in aes() to order the x variable by the y variable

ggplot(votedata %>% filter(year == 2000)) + geom_col(aes(x = reorder(state, demVote), y = demVote)) + coord_flip()

So, what if I want to see what the north and south states did different?

start with a facet_wrap using the south variable:

ggplot(votedata %>% filter(year == 2000)) + geom_col(aes(x = reorder(state, demVote), y = demVote)) + coord_flip() + facet_wrap(~ south)

Okay, that’s not great. Lets color by south instead.

ggplot(votedata %>% filter(year == 2000)) + geom_col(aes(x = reorder(state, demVote), y = demVote, fill = south)) + coord_flip() 

I’m a good data scientist, so I want my plot to have a name! and my axes to have lables! Use labs to add a title, subtitle, and x and y labels.

ggplot(votedata %>% filter(year == 2000)) + 
  geom_col(aes(x = reorder(state, demVote), y = demVote, fill = south)) + 
  coord_flip() + 
  labs(title = "Percent Dem Vote by State, in 2000",
       subtitle = "Colored by State location", 
       x = "State",
       y = "% Votes Democratic")

You can move the legend with theme(legend.position = "bottom")

ggplot(votedata %>% filter(year == 2000)) + 
  geom_col(aes(x = reorder(state, demVote), y = demVote, fill = south)) + 
  coord_flip() + 
  labs(title = "Percent Dem Vote by State, in 2000",
       subtitle = "Colored by State location", 
       x = "State",
       y = "% Votes Democratic") + 
  theme(legend.position = "bottom")

What else could we facet by? years! Let’s filter to year in 2008 and 2016, then facet by years.

ggplot(votedata %>% filter(year == 2008 | year == 2016)) + 
  geom_col(aes(x = reorder(state, demVote), y = demVote, fill = south)) + 
  coord_flip() + 
  facet_wrap(~ year) + 
  labs(title = "Percent Dem Vote by State, in 2000",
       subtitle = "Colored by State location", 
       x = "State",
       y = "% Votes Democratic") + 
  theme(legend.position = "bottom")

## this has the issue of having weird sorting things, since each graph is a different ordering! 

We need to know who won! We could add a vertical line at 50 for who got more, to indicate the majority of votes. Adding the layer geom_hline() adds a horizontal line. (What do you guess geom_vline() would do?)

ggplot(votedata %>% filter(year == 2008 | year == 2016)) + 
  geom_col(aes(x = reorder(state, demVote), y = demVote, fill = south)) + 
  coord_flip() + 
  facet_wrap(~ year) + 
  labs(title = "Percent Dem Vote by State, in 2000",
       subtitle = "Colored by State location", 
       x = "State",
       y = "% Votes Democratic") + 
  theme(legend.position = "bottom") + 
  geom_hline(yintercept = 50)

Getting fancy with a map!

When using geom_polygon or geom_map, you will typically need two data frames:

  • one contains the coordinates of each polygon (positions)
  • the other the values associated with each polygon (values).

An id variable links the two together.

Run the below code to get a map graph.

library(maps)
## 
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
## 
##     map
votedata$state <- tolower(votedata$state)  ## states need to be lowercase for linking

states_map <- map_data("state") ## this gives us the lat and long for each point of each state.
  
map_plot <-  ggplot(data =  votedata %>% filter(year == 2008), aes(map_id = state)) +
    geom_map(aes(fill = demVote), map = states_map) +
    expand_limits(x = states_map$long, y = states_map$lat)
map_plot  

map_plot <-  ggplot(data =  votedata %>% filter(year == 2016), aes(map_id = state)) +
  geom_map(aes(fill = demVote), map = states_map)+
  expand_limits(x = states_map$long, y = states_map$lat)
map_plot  

What if I want a map that shows which of the states are “south”? What do I change?

map_plot <-  ggplot(data =  votedata %>% filter(year == 2016), aes(map_id = state)) +
  geom_map(aes(fill = south), map = states_map)+
  expand_limits(x = states_map$long, y = states_map$lat)
map_plot  

Some more dplyr practice

I want to know the average democratic vote for N vs S, by year.

First, find the average democratic votes for the north and the south, every year. You’ll need to do a double group_by() here. You do it in one call of the function.

votedata %>% group_by(south, year) %>% summarise(mean_dem = mean(demVote))
## `summarise()` has grouped output by 'south'. You can override using the
## `.groups` argument.
## # A tibble: 44 × 3
## # Groups:   south [2]
##    south  year mean_dem
##    <lgl> <int>    <dbl>
##  1 FALSE  1932     56.7
##  2 FALSE  1936     59.2
##  3 FALSE  1940     52.8
##  4 FALSE  1944     51.1
##  5 FALSE  1948     50.2
##  6 FALSE  1952     40.9
##  7 FALSE  1956     40.1
##  8 FALSE  1960     48.0
##  9 FALSE  1964     63.0
## 10 FALSE  1968     44.7
## # ℹ 34 more rows

Then, let’s plot that! Pipe the result of your group_by and summarize to ggplot and geom_line(), with year on the x axis and your summarized value on the y axis. Color by the south variable.

votedata %>% 
  group_by(south, year) %>% 
  summarise(mean_dem = mean(demVote)) %>% 
  ggplot(aes(x = year, y = mean_dem, color = south)) + geom_line()
## `summarise()` has grouped output by 'south'. You can override using the
## `.groups` argument.

Layering plots!

Penguins!

library(palmerpenguins)
glimpse(penguins)
## Rows: 344
## Columns: 8
## $ species           <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
## $ island            <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
## $ bill_length_mm    <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
## $ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
## $ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
## $ body_mass_g       <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
## $ sex               <fct> male, female, female, NA, female, male, female, male…
## $ year              <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…

We can use boxplots to visualize the distribution of weight (body_mass_g) within each species:

ggplot(penguins, aes(x = body_mass_g, y = species)) + geom_boxplot()
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

What if we also want the points? Layering!! Add a geom_point to your existing boxplot. geom_boxplot + geom_point!

ggplot(penguins, aes(x = body_mass_g, y = species)) + geom_boxplot() + geom_point()
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

But, these are all stacked up… to actually see them, use “geom_jitter” instead of points

ggplot(penguins, aes(x = body_mass_g, y = species)) + geom_boxplot() + geom_jitter()
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

How to get the boxplots on top? The layers are plotted in the order you give them, so change to geom_point + geom_boxplot. (You might want to change the alpha on the boxplot to be able to see the plots under them)

ggplot(penguins, aes(x = body_mass_g, y = species))  + geom_jitter() + geom_boxplot(alpha = 0.5)
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

Maybe let’s try replacing the boxplot with a geom_violin()?

ggplot(penguins, aes(x = body_mass_g, y = species))  + geom_jitter() + geom_violin(alpha = 0.5)
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_ydensity()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

If time: More Practice with Penguins